package router

import (
	"car-trade-mgr/handler"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func Init() *gin.Engine {
	r := gin.Default()

	r.Use(Cors())

	r.Static("/static", "./static")

	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})

	//权限
	r.POST("/user/login", handler.Login)
	r.POST("/user/userRoleAdd", handler.UserRoleAdd)
	r.POST("/user/roleNodeAdd", handler.RoleNodeAdd)
	r.GET("/user/userRoleList", handler.UserRoleList)
	r.GET("/user/roleNodeList", handler.RoleNodeList)

	//车辆交易订单
	r.POST("/car/carAdd", handler.CarAdd)
	r.POST("/car/carOrderAdd", handler.CarOrderAdd)
	r.GET("/car/carOrderList", handler.CarOrderList)
	r.GET("/car/carOrderDetail", handler.CarOrderDetail)

	//车辆数据信息
	r.POST("/carMer/carMerAdd", handler.CarMerAdd)
	r.POST("/carMer/carTypeAdd", handler.CarTypeAdd)
	r.GET("/carMer/carMerList", handler.CarMerList)
	r.GET("/carMer/carMerDetail", handler.CarMerDetail)

	//车辆交易合同
	r.POST("/carContract/carConAdd", handler.CarConAdd)
	r.POST("/carContract/carContractAdd", handler.CarContractAdd)
	r.GET("/carContract/carContractList", handler.CarContractList)
	r.GET("/carContract/carContractDetail", handler.CarContractDetail)

	return r
}
